package com.weilele.mvvm.utils.permission

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import androidx.core.app.ActivityCompat
import com.weilele.mvvm.base.*
import com.weilele.mvvm.packageName
import com.weilele.mvvm.utils.coroutine.awaitAny
import com.weilele.mvvm.utils.printStackTrace
import com.weilele.mvvm.utils.result_contract.requestPermissions
import okhttp3.internal.ignoreIoExceptions
import kotlin.coroutines.resume

/**
 * 发送通知
 */
private fun listenerIt(result: Map<String, Boolean>, permissionListener: (List<String>) -> Unit) {
    val list = mutableListOf<String>()
    for ((permission, bool) in result) {
        if (!bool) {
            list.add(permission)
        }
    }
    permissionListener.invoke(list)
}

/**
 * 请求权限
 */
fun MvvmActivity.callPermissions(
    permission: List<String>,
    permissionListener: Function1<List<String>/*被拒绝的权限集合*/, Unit>
) {
    checkAndRequest(permission, permissionListener) {
        requestPermissions(it, null) { result ->
            listenerIt(result, permissionListener)
        }
    }
}

/**
 * 请求权限
 */
suspend fun MvvmActivity.callPermissionsAwait(permission: List<String>): List<String> {
    return awaitAny {
        callPermissions(permission) { list/*被拒绝的权限集合*/ ->
            it.resume(list)
        }
    }
}

/**
 * 请求权限
 */
fun MvvmFragment.callPermissions(
    permission: List<String>,
    permissionListener: Function1<List<String>/*被拒绝的权限集合*/, Unit>
) {
    context?.checkAndRequest(permission, permissionListener) {
        requestPermissions(it, null) { result ->
            listenerIt(result, permissionListener)
        }
    }
}

/**
 * 请求权限
 */
suspend fun MvvmFragment.callPermissionsAwait(permission: List<String>): List<String> {
    return awaitAny {
        callPermissions(permission) { list/*被拒绝的权限集合*/ ->
            it.resume(list)
        }
    }
}

/**
 * 请求权限
 */
fun MvvmDialog.callPermissions(
    permission: List<String>,
    permissionListener: Function1<List<String>/*被拒绝的权限集合*/, Unit>
) {
    context?.checkAndRequest(permission, permissionListener) {
        requestPermissions(it, null) { result ->
            listenerIt(result, permissionListener)
        }
    }
}

/**
 * 请求权限
 */
suspend fun MvvmDialog.callPermissionsAwait(permission: List<String>): List<String> {
    return awaitAny {
        callPermissions(permission) { list/*被拒绝的权限集合*/ ->
            it.resume(list)
        }
    }
}

/**
 * 检查并请求
 */
private fun Context.checkAndRequest(
    permission: List<String>, permissionListener: Function1<List<String>/*被拒绝的权限集合*/, Unit>,
    request: Function1<Array<String>, Unit>
) {
    //没有权限
    val unGetPermission = checkPermission(permission)
    if (unGetPermission.isNotEmpty()) {
        request.invoke(unGetPermission.toTypedArray())
    } else {
        permissionListener.invoke(listOf())
    }
}

/**
 * 检查是否获取到了某权限
 * 返回值，true 有了该权限
 * false 没有此权限
 */
fun Context.checkPermission(permission: String): Boolean {
    return ActivityCompat.checkSelfPermission(
        this,
        permission
    ) == PackageManager.PERMISSION_GRANTED
}

/**
 * 检查是否获取到了某权限
 * 返回值，没有获得权限的集合
 */
fun Context.checkPermission(permissions: List<String>): MutableList<String> {
    val unGetPermissions = mutableListOf<String>()
    permissions.forEach {
        if (!checkPermission(it)) {
            unGetPermissions.add(it)
        }
    }
    return unGetPermissions
}

/**
 * 获取存储权限,兼容不同版本
 * [Manifest.permission.WRITE_EXTERNAL_STORAGE]
 * [Manifest.permission.READ_EXTERNAL_STORAGE]
 * [Manifest.permission.MANAGE_EXTERNAL_STORAGE]
 */
fun MvvmActivity.callStoragePermission(listener: (agree: Boolean) -> Unit) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        // 先判断有没有权限
        if (Environment.isExternalStorageManager()) {
            //有权限
            listener.invoke(true)
        } else {
            try {
                val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                intent.data = Uri.parse("package:$packageName")
                navigateForResultHelper.navigateForResult(intent) { resultCode, data ->
                    listener.invoke(Environment.isExternalStorageManager())
                }
            } catch (e: Exception) {
                printStackTrace { e }
                listener.invoke(false)
            }
        }
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        callPermissions(
            listOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        ) {
            listener.invoke(it.isEmpty())
        }
    }
}

/**
 * 获取存储权限,兼容不同版本
 * [Manifest.permission.WRITE_EXTERNAL_STORAGE]
 * [Manifest.permission.READ_EXTERNAL_STORAGE]
 * [Manifest.permission.MANAGE_EXTERNAL_STORAGE]
 */
fun MvvmFragment.callStoragePermission(listener: (agree: Boolean) -> Unit) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        // 先判断有没有权限
        if (Environment.isExternalStorageManager()) {
            //有权限
            listener.invoke(true)
        } else {
            try {
                val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                intent.data = Uri.parse("package:$packageName")
                navigateForResultHelper.navigateForResult(intent) { resultCode, data ->
                    listener.invoke(Environment.isExternalStorageManager())
                }
            } catch (e: Exception) {
                printStackTrace { e }
                listener.invoke(false)
            }
        }
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        callPermissions(
            listOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        ) {
            listener.invoke(it.isEmpty())
        }
    }
}